package com.ay.demo.akka.share;

import com.ay.demo.akka.msg.Message;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.contrib.pattern.ClusterSharding;
import akka.contrib.pattern.ShardRegion.MessageExtractor;

public class ShareContext {
	
	private static final String SHARE_PROXY = "share_proxy";
	private ActorSystem actorSystem;
	
	/**
	 * @see ClusterSharding.deliverMessage()
	 */
	private MessageExtractor shareMessageExtractor = new MessageExtractor() {
		@Override
		public String shardId(Object msg) {
			if (msg instanceof Message) {
				return String.valueOf(((Message) msg).getMid());
			}
			return null;
		}
		@Override
		public Object entryMessage(Object msg) {
			return msg;
		}
		/**<pre>
		 * 根据返回会的String来创建接收消息的Actor;
		 * 返回结果相同则接收消息为同一Actor对象.
		 */
		@Override
		public String entryId(Object msg) {
			if (msg instanceof Message) {
//				return "0";
				return String.valueOf(((Message) msg).getMid() % 10);
			}
			return null;
		}
	};

	public ShareContext(ActorSystem actorSystem) {
		super();
		this.actorSystem = actorSystem;
		ActorRef actorRef = ClusterSharding.get(actorSystem).start(SHARE_PROXY, Props.create(ShareActor.class), shareMessageExtractor);
		System.out.println(String.format("ShareContext, share_proxy:%s", actorRef));
	}

	public ActorRef getProxy() {
		return ClusterSharding.get(actorSystem).shardRegion(SHARE_PROXY);
	}
	
}
